package net.expectx.pay.controller;

import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseResult;
import net.expectx.common.single.util.Md5Util;
import net.expectx.pay.common.AdminConstants;
import net.expectx.pay.common.AdminResult;
import net.expectx.pay.common.util.ExpectXUtil;
import net.expectx.pay.dao.bean.MerchantUser;
import net.expectx.pay.dao.bean.MerchantUserExample;
import net.expectx.pay.dao.bean.PermissionUser;
import net.expectx.pay.dao.bean.PermissionUserExample;
import net.expectx.pay.rpc.api.PermissionUserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hxs
 */
@Controller
@RequestMapping("manager/permissionUser")
public class PermissionUserController {
    @Autowired
    private PermissionUserService permissionUserService;

    @ApiOperation(value = "用户主页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "permissionUser/index";
    }

    @ApiOperation(value = "新增用户")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create(ModelMap modelMap) {
        return "permissionUser/modify";
    }

    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") Long id, ModelMap modelMap) {
        PermissionUserExample permissionUserExample = new PermissionUserExample();
        PermissionUserExample.Criteria criteria = permissionUserExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andIdEqualTo(id);
        List<PermissionUser> permissionUsers = permissionUserService.selectByExample(permissionUserExample);
        if (permissionUsers.size()!=0){
            PermissionUser permissionUser = permissionUsers.get(0);
            modelMap.put("permissionUsers",permissionUser);
        }
        return "permissionUser/modify";
    }

    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/alterPassword", method = RequestMethod.GET)
    public String alterPassword() {
        return "permissionUser/alterPassword";
    }


    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Object page(
            @RequestParam(required = false, defaultValue = "1", value = "page") int page,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            HttpServletRequest request) {
        PermissionUserExample permissionUserExample = new PermissionUserExample();
        PermissionUserExample.Criteria criteria = permissionUserExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);

        String userName = request.getParameter("userName");
        if (StringUtils.isNotBlank(userName)) {
            criteria.andUserNameLike("%"+userName+"%");
        }

        permissionUserExample.setPageIndex(page);
        permissionUserExample.setPageSize(limit);
        permissionUserExample.setOrderByClause("gmt_modified desc");

        List<PermissionUser> permissionUsers = permissionUserService.selectByExample(permissionUserExample);
        long total = permissionUserService.countByExample(permissionUserExample);
        Map<String, Object> result = new HashMap<>(16);
        result.put("code", AdminConstants.LAYUI_DATA_OK);
        result.put("count", total);
        result.put("msg", "");
        result.put("data", permissionUsers);
        return result;
    }

    @ApiOperation(value = "新增用户")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create( PermissionUser permissionUser) {
        PermissionUserExample permissionUserExample = new PermissionUserExample();
        PermissionUserExample.Criteria criteria = permissionUserExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andUserNameEqualTo(permissionUser.getUserName());
        List<PermissionUser> permissionUsers = permissionUserService.selectByExample(permissionUserExample);
        if (permissionUsers.size()==0){
            permissionUser.setGmtCreate(System.currentTimeMillis());
            permissionUser.setGmtModified(System.currentTimeMillis());
            permissionUser.setSalt(UUID.randomUUID().toString().toLowerCase().replace("-",""));
            permissionUser.setPassword(Md5Util.md5(permissionUser.getPassword()+permissionUser.getSalt()));
            if (permissionUserService.insertSelective(permissionUser).isSuccess()){
                return  new AdminResult(true);
            }
            return new AdminResult(false,200,"新增失败","");
        }
        return  new AdminResult(false,200,"用户已存在","");
    }


    @ApiOperation(value = "修改用户")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") Long id, PermissionUser permissionUser) {
        permissionUser.setGmtModified(System.currentTimeMillis());
        return permissionUserService.updateByPrimaryKeySelective(permissionUser);
    }

    @ApiOperation(value = "删除用户")
    @RequestMapping(value = "/delete/{ids}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        PermissionUserExample permissionUserExample = new PermissionUserExample();
        permissionUserExample.createCriteria().andIdIn(ExpectXUtil.toList(ids, ","));
        return permissionUserService.physicalRemoveByExample(AdminConstants.YES,permissionUserExample);
    }



    @ApiOperation(value = "修改密码")
    @RequestMapping(value = "/alterPassword", method = RequestMethod.POST)
    @ResponseBody
    public Object alterPassword(String oldpass,String newpass) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        PermissionUser permissionUser =(PermissionUser) session.getAttribute("permissionUser");
        if (permissionUser.getPassword().toLowerCase().equals(Md5Util.md5(oldpass + permissionUser.getSalt()))){
            permissionUser.setPassword(Md5Util.md5(newpass+permissionUser.getSalt()));
            return permissionUserService.updateByPrimaryKey(permissionUser);
        }
        return new BaseResult(false,"原始密码错误",null);
    }

}
